package com.qiwenshare.file.controller;

import cn.hutool.core.net.URLEncodeUtil;
import com.aizuda.limiter.annotation.DistributedLock;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.common.SSOConstants;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.security.token.SSOToken;
import com.dtflys.forest.Forest;
import com.dtflys.forest.annotation.URLEncode;
import com.dtflys.forest.http.ForestRequest;
import com.google.common.collect.Maps;
import com.qiniu.util.Json;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import javafx.application.Application;
import javafx.stage.Stage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

@Controller
@Slf4j
@RequestMapping("/sso")
public class SSOController {

    @Value("${check.ticket.url}")
    private String checkTicketUrl;

    @Value("${uc.config.login-url}")
    private String ssoUserCenter;

    @Value("${uc.config.logout-url}")
    private String ssoUserCenterLogout;

    @RequestMapping("/")
    public void toLogin(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException {
        //1.如果请求参数中存在token 需要验证token是否有效，验证有效则提取token用户ID 创建局部会话
        //2.如果请求参数不存在token 则判断本地cookie是否有内容 如果仍然没有
        String token = req.getParameter("token");
        //resp.setHeader("Access-Control-Allow-Origin",req.getHeader("Origin"));
        //resp.setHeader("Access-Control-Allow-Credentials","true");
        log.info("token={}",token);
        if(token == null ){
            token = SSOHelper.attrToken(req)!=null?SSOHelper.attrToken(req).getToken():null;
            if(token == null)
                return;
        }
        ForestRequest request = Forest.get(checkTicketUrl).addHeader("token",token);
        String verifyTicketResult = request.executeAsString();
        JSONObject response = JSON.parseObject(verifyTicketResult);
        Integer code = (Integer)response.get("code");
        log.info("code={}",code);
        if(code.intValue()!=0) {
            resp.sendRedirect(HttpUtil.encodeRetURL(ssoUserCenter,"url","http://slg.cogonline.com/home"));
            return;
        }
        SSOToken st = SSOHelper.attrToken(req)==null?SSOToken.create(Jwts.builder()):SSOHelper.attrToken(req);
        Map<String,Object> map = (Map<String,Object>)response.get("data");
        //map.put("token",req.getParameter("token"));
        st.setToken(req.getParameter("token"));
        st.setId(map.get("id"));
        st.setIssuer("cogonline");
        Integer exp = (Integer)map.get("vip_expiretime");
        Long now = System.currentTimeMillis();
        log.info("exp={}",exp);
        st.getJwtBuilder().setClaims(map).setExpiration(new Date(exp!=null?exp.longValue():now.longValue()+SSOConfig.getInstance().getCookieMaxAge()));
        Integer det = SSOConfig.getInstance().getCookieMaxAge()/1000;
        req.setAttribute(SSOConstants.SSO_COOKIE_MAXAGE,exp!=null?(exp-now.intValue())/1000:det);
        SSOHelper.setCookie(req,resp,st,false);
        log.info("客户端跳转");
        resp.sendRedirect("/home");
    }

    @GetMapping("/logonout")
    @SneakyThrows
    public void toLogout(HttpServletRequest req, HttpServletResponse resp){
        log.info("退出系统");
        //SSOHelper.clearRedirectLogin(req,resp);
        SSOHelper.clearLogin(req,resp);
        resp.sendRedirect(URLEncodeUtil.encode(ssoUserCenterLogout));
    }
}
